import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_common_utils/src/extends/context_extends.dart';
import 'package:flutter_common_utils/src/extends/string_extends.dart';
import 'package:flutter_common_utils/src/store/store_utils.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:uuid/uuid.dart';

import 'file/file_utils.dart';
import 'log/log.dart';
import 'other/timezone.dart';

class AppUtils {
  AppUtils._();

  //全局 GlobalKey
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  //全局 BuildContext
  static BuildContext get context => navigatorKey.currentContext!;
  static late PackageInfo packageInfo;
  static late DeviceInfoPlugin deviceInfoPlugin;
  static late BaseDeviceInfo baseDeviceInfo;

  //devicePixelRatio
  static double get dpr => context.dpr;

  /// 屏幕宽高
  static double get width => context.widthMq;

  static double get height => context.heightMq;

  static bool get isAndroid => !isWeb && Platform.isAndroid;

  static bool get isIOS => !isWeb && Platform.isIOS;

  static bool get isLinux => !isWeb && Platform.isLinux;

  static bool get isWindows => !isWeb && Platform.isWindows;

  static bool get isMacOS => !isWeb && Platform.isMacOS;

  static bool get isDesktop => isMacOS || isWindows || isLinux;

  static bool get isMobile => isAndroid || isIOS;

  static bool get isWeb => kIsWeb;
  static Map<String, String> mccMncMap = {};

  static Future<void> init() async {
    LogUtils.runInit();
    LogUtils.setEnable(isDebug);
    await _initDeviceInfo();
    await FileUtils.init();
    await TimeZoneUtils.init();
  }

  static initWithNavigatorKey({GlobalKey<NavigatorState>? key}) {
    if (key != null) {
      navigatorKey = key;
    }
  }

  ///初始化信息
  static Future<void> _initDeviceInfo() async {
    if (!isWeb) {
      WidgetsFlutterBinding.ensureInitialized();
    }
    packageInfo = await PackageInfo.fromPlatform();
    deviceInfoPlugin = DeviceInfoPlugin();
    baseDeviceInfo = await deviceInfoPlugin.deviceInfo;
  }

  static String get platform {
    return AppUtils.isWindows
        ? "windows"
        : AppUtils.isAndroid
            ? "android"
            : AppUtils.isMacOS
                ? "macOS"
                : AppUtils.isIOS
                    ? "iOS"
                    : "";
  }

  //APP名称
  static String get appName => packageInfo.appName;

  //包名
  static String get packageName => packageInfo.packageName;

  //版本名
  static String get version => packageInfo.version;

  //版本号
  static String get versionCode => packageInfo.buildNumber;

  static bool get isBeta => isDebug || version.contains("beta");

  static bool get isDebug => kDebugMode;

  static AndroidDeviceInfo get androidInfo => baseDeviceInfo as AndroidDeviceInfo;

  static IosDeviceInfo get iosInfo => baseDeviceInfo as IosDeviceInfo;

  static LinuxDeviceInfo get linuxInfo => baseDeviceInfo as LinuxDeviceInfo;

  static MacOsDeviceInfo get macOsInfo => baseDeviceInfo as MacOsDeviceInfo;

  static WindowsDeviceInfo get windowsInfo => baseDeviceInfo as WindowsDeviceInfo;

  static WebBrowserInfo get webBrowserInfo => baseDeviceInfo as WebBrowserInfo;

  //设备ID
  static String getDeviceId() {
    try {
      if (AppUtils.isAndroid) {
        if (androidInfo.id.isEmpty) {
          return getOrCreateAppUuid();
        } else {
          // Android ID（非硬件唯一，可重置）
          return androidInfo.id;
        }
      } else if (AppUtils.isIOS) {
        if (iosInfo.identifierForVendor.isNullOrEmpty()) {
          return getOrCreateAppUuid();
        } else {
          // iOS 供应商 ID（应用卸载后重置）
          return iosInfo.identifierForVendor.orEmpty();
        }
      } else if (AppUtils.isLinux) {
        if (linuxInfo.machineId.isNullOrEmpty()) {
          return getOrCreateAppUuid();
        } else {
          // Linux 机器 ID
          return linuxInfo.machineId.orEmpty();
        }
      } else if (AppUtils.isMacOS) {
        if (macOsInfo.systemGUID.isNullOrEmpty()) {
          return getOrCreateAppUuid();
        } else {
          // MacOS 系统GUID
          return macOsInfo.systemGUID.orEmpty();
        }
      } else if (AppUtils.isWindows) {
        if (windowsInfo.deviceId.isNullOrEmpty()) {
          return getOrCreateAppUuid();
        } else {
          // Windows
          return windowsInfo.deviceId.orEmpty();
        }
      }
      return getOrCreateAppUuid();
    } catch (e, s) {
      LogUtils.e("Error getting device ID", error: e, stackTrace: s);
      return getOrCreateAppUuid();
    }
  }

  static String getBrand() {
    if (AppUtils.isAndroid) {
      return androidInfo.brand;
    } else if (AppUtils.isIOS) {
      return iosInfo.name;
    } else if (AppUtils.isMacOS) {
      return macOsInfo.model;
    } else if (AppUtils.isLinux) {
      return "Linux";
    } else if (AppUtils.isWindows) {
      return "Windows";
    } else if (AppUtils.isWeb) {
      return "Web";
    }
    return "";
  }

  static String getModel() {
    if (AppUtils.isAndroid) {
      return androidInfo.model;
    } else if (AppUtils.isIOS) {
      return iosInfo.modelName;
    } else if (AppUtils.isMacOS) {
      return macOsInfo.modelName;
    } else if (AppUtils.isLinux) {
      return "Linux";
    } else if (AppUtils.isWindows) {
      return "Windows";
    } else if (AppUtils.isWeb) {
      return "Web";
    }
    return "";
  }

  static String getOSVersion() {
    if (AppUtils.isAndroid) {
      return androidInfo.version.release;
    } else if (AppUtils.isIOS) {
      return iosInfo.systemVersion;
    } else if (AppUtils.isMacOS) {
      return macOsInfo.kernelVersion;
    } else if (AppUtils.isLinux) {
      return linuxInfo.version.orEmpty();
    } else if (AppUtils.isWindows) {
      return windowsInfo.displayVersion;
    }
    return "";
  }

  static String getOrCreateAppUuid() {
    String uuid = 'app_uuid'.getStore();
    if (uuid.isEmpty) {
      uuid = const Uuid().v4(); // 生成随机 UUID
      'app_uuid'.putStore(uuid);
    }
    return uuid;
  }

  //获取当前时区
  static String getTimeZone() {
    // 刷新时区,让下次时区刷新生效
    TimeZoneUtils.refresh();
    return TimeZoneUtils.timezone?.identifier ?? '';
  }

  // 设置屏幕方向 竖屏
  static Future<void> setScreenPortrait() {
    return SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, // 只允许竖屏
      // DeviceOrientation.landscapeLeft, // 如果允许横屏请取消注释
      // DeviceOrientation.landscapeRight,
    ]);
  }

  // 设置屏幕方向 横屏
  static Future<void> setScreenLandscape() {
    return SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft, // 只允许横屏
      // DeviceOrientation.portraitUp, // 如果允许竖屏请取消注释
      // DeviceOrientation.landscapeRight,
    ]);
  }

  // 设置屏幕方向 横竖屏都可以
  static Future<void> setScreenAny() {
    return SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }
}
